package com.cff.pm.client;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpSpider implements HttpSpider{
	private String clientKey = "";
	private OkHttpClient oc = null;
	
	public OkHttpSpider(){
		initClient();
	}
	
	public void initClient(){
		UUID uuid = UUID.randomUUID(); 
		clientKey = uuid.toString().replace("-", "");
		
		oc = new OkHttpClient.Builder().connectTimeout(SECOND_TIMEOUT, TimeUnit.MILLISECONDS) // 设置连接超时
				.readTimeout(SECOND_TIMEOUT, TimeUnit.MILLISECONDS) // 设置读超时
				.writeTimeout(SECOND_TIMEOUT, TimeUnit.MILLISECONDS) // 设置写超时
				.retryOnConnectionFailure(true) // 是否自动重连
				.cookieJar(new ClinetCookieJar(clientKey)).build();

	}
	
	
	@Override
	public String doPostWithJsonResult(String uri, Map<String, String> paramMap) throws IOException {
		RequestBody formBody = null;
		Charset UTF_8 = Charset.forName("UTF-8");
		FormBody.Builder formEncodingBuilder = new FormBody.Builder(UTF_8);
		if (paramMap != null && !paramMap.isEmpty()) {
			for (String key : paramMap.keySet()) {
				formEncodingBuilder.add(key, paramMap.get(key));
			}
		}
		formBody = formEncodingBuilder.build();

		Request request = new Request.Builder().url(uri).post(formBody).build();
		Response response = oc.newCall(request).execute();
		if (!response.isSuccessful())
			throw new IOException("Unexpected code " + response);

		String json = null;
		json = response.body().string();

		return json;
	}
	
	@Override
	public String doGetWithJsonResult(String uri) throws IOException {
		Request request = new Request.Builder().url(uri).build();
		Response response = oc.newCall(request).execute();
		if (!response.isSuccessful())
			throw new IOException("Unexpected code " + response);

		String json = null;
		json = response.body().string();
		return json;
	}
	
	
	public OkHttpClient getOc() {
		return oc;
	}
	public void setOc(OkHttpClient oc) {
		this.oc = oc;
	}
	
}
